/**
 * 
 */
package com.surelution.lansao.wxmp

import com.surelution.lansao.Item;
import com.surelution.lansao.Member
import com.surelution.lansao.MemberAddress;
import com.surelution.lansao.Order;
import com.surelution.lansao.OrderItem
import com.surelution.lansao.OrderStatus;
import com.surelution.lansao.Partner;
import com.surelution.lansao.WaitingFor
import com.surelution.whistle.core.Attribute;

/**
 * @author <a href="mailto:guangzong.syu@gmail.com">Guangzong</a>
 *
 */
class OrderAction extends BaseLansaoAction{
	private ArrayList<OrderItem> orderItems

	/* (non-Javadoc)
	 * @see com.surelution.whistle.core.BaseAction#accept()
	 */
	@Override
	public boolean accept() {
		orderItems = new ArrayList<OrderItem>()
		boolean parseFailed = false
		def sns = []
		char c = 'a'
		def items = Item.list()
		items.each {
			sns.add(c)
			c++
		}
		String content = getParam(Attribute.KEY_Content)
		content = content.trim()
		content.split("\n").each {line->
			char sn
			int amount = 1
			line = line.trim()
			String[] ss = line.split(" ")
			if(ss.length == 1) {
				String s = ss[0].trim()
				if(s.length() == 1) {
					char ch = s.charAt(0)
					if(sns.contains(ch)) {
						sn = ch
					} else {
						parseFailed = true
					}
				} else {
					parseFailed = true
				}
			} else if(ss.length == 2) {
				String s = ss[0]
				char ch = s.charAt(0)
				if(sns.contains(ch)) {
					sn = ch
				} else {
						parseFailed = true
				}
				try{
					amount = Integer.parseInt(ss[1])
				}catch(e) {
					parseFailed = true
				}
			} else {
				parseFailed = true
			}
			def item = items[sn - c]
			def orderItem = new OrderItem(item:item, amount:amount)
			orderItems.add(orderItem)
		}
		return (orderItems.size() > 0) && !parseFailed;
	}

	/* (non-Javadoc)
	 * @see com.surelution.whistle.core.BaseAction#execute()
	 */
	@Override
	public void execute() {
		StringBuilder sb = new StringBuilder()
		sb.append("您已订购")
		float total = 0
		orderItems.each {
			sb.append("${it.item.name}${it.amount}份,")
			total += it.item.price * it.amount
		}
		def toUserName = getParam(Attribute.KEY_ToUserName)
		def partner = Partner.findByWxOpenId(toUserName)
		if(partner) {
			Member member = getMember()
			MemberAddress ma = MemberAddress.findSuitableAddress(member)
			def orderStatus
			sb.append("共${total}元，我们将在12点前送达")
			if(!ma) {
				orderStatus = OrderStatus.findByKey(OrderStatus.NEW)
				def createdAt = new Date()
				def expiredAt = new Date(createdAt.time + 60 * 5 * 1000)
				def waitingFor = new WaitingFor(member:member, createdAt:createdAt,expiredAt:expiredAt, finished : false)
				waitingFor.save(flush:true)
				sb.append("\n您还没有登记送餐地址，请立即回复送餐地址，如：招商局大厦24楼2402\n我们收到后进行验证，会给您回复确认。下次订餐，如果您不修改送餐地址，无需再次发送送餐地址。我们期待您的回复。");
			} else if(ma.verified) {
				orderStatus = OrderStatus.findByKey(OrderStatus.CONFIRMED)
				sb.append("\n您的送餐地址是：")
				sb.append(ma)
			} else {
				orderStatus = OrderStatus.findByKey(OrderStatus.NEW)
				sb.append("\n您登记了送餐地址（${ma.address}），但是我们的工作人员还没有确认该地址的有效性，请稍候，或者立即回复送餐地址")
			}
			Order order = new Order(partner:partner, member:member, orderTime: new Date(), status:orderStatus)
			order.save(flush:true)
			orderItems.each {
				it.order = order
				it.save(flush:true)
			}

			put(new Attribute(Attribute.KEY_Content, sb.toString()))
		}
	}

}
